package com.rongkang.interview.juc.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 阻塞队列
 * @author: 荣康
 * @date: 2021/12/8
 * <p>
 * <p>
 * volatile/CAS/atomicInteger/BlockQueue/线程交互/原子引用
 */
public class BlockQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        //创建一个有界的队列
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<String>(3);
        /*
        //抛出异常 add(),remove()
        System.out.println(blockingQueue.add("111"));
        System.out.println(blockingQueue.add("222"));
        System.out.println(blockingQueue.add("333"));
//        System.out.println(blockingQueue.add("444")); //抛出异常  add()和remove()方法都抛出异常
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
//        System.out.println(blockingQueue.remove());//抛出异常*/
        System.out.println("=================================");

      /*  //特殊值 offer(),poll()
        System.out.println(blockingQueue.offer("1"));
        System.out.println(blockingQueue.offer("2"));
        System.out.println(blockingQueue.offer("3"));
        System.out.println(blockingQueue.offer("4"));//队列满了，在添加会返回false
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());//队列为空了再去取，此时会返回null*/
        System.out.println("=================================");
/*        //阻塞队列  put(),take()
        blockingQueue.put("1");
        blockingQueue.put("2");
        blockingQueue.put("3");
//        blockingQueue.put("4"); // 此时会阻塞线程
        blockingQueue.take();
        blockingQueue.take();
        blockingQueue.take();
//        blockingQueue.take(); //内容不存在也会阻塞线程*/
        System.out.println("==================================");
        //不见不散组
        System.out.println(blockingQueue.offer("11", 11L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("22", 11L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("33", 11L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("44", 11L, TimeUnit.SECONDS));//此时要是等待两秒还插入不进去，就打印false
        System.out.println(blockingQueue.poll(2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2L, TimeUnit.SECONDS));//取不到就为null
    }
}
